import time


# 定义不带参数的装饰器（用来计算func调用前后的时间），就是嵌套函数
def timmer(func):
    def wrapper():
        start_time = time.time()
        func()
        end_time = time.time()
        print("decorator-no-param: %s runs for %s seconds" % (func.__name__, (end_time - start_time)))
    return wrapper

# 使用不带参数的装饰器
@timmer
def sleep_a_while():
    time.sleep(1)


sleep_a_while()         # sleep_a_while runs for 1.0010671615600586 seconds


# 定义带参数的装饰器
def tips(func):
    def inner(a, b):
        print(func(a, b))
        print('decorator-with-param: %s' % func.__name__)
    return inner

# 使用带参数的装饰器
@tips
def get_max(x, y):
    if x > y:
        return x
    else:
        return y


get_max(3, 5)
# 5
# decorator-with-param: get_max


# 定义带参数和修饰符的装饰器
def wrapper_tips(arg):
    def tips(func):
        def inner(a, b):
            func(a, b)
            print('decorator-with-param-with-modifier: %s() %s' % (func.__name__, arg))
        return inner
    return tips

# 使用带参数和修饰符的装饰器
@wrapper_tips('add')
def add(x, y):
    print(x + y)

# 使用带参数和修饰符的装饰器
@wrapper_tips('sub')
def sub(x, y):
    print(x - y)


add(2, 3)
# 5
# decorator-with-param-with-modifier: add() add
sub(3, 2)
# 1
# decorator-with-param-with-modifier: sub() sub

